// src/generators/utils.ts
import fs from 'fs-extra';
import path from 'path';
import { logger } from '../utils/logger';

// 检查目录是否存在
export const checkDirectoryExists = async (dirPath: string): Promise<boolean> => {
  const exists = await fs.pathExists(dirPath);
  if (exists) {
    logger.warning(`目录已存在: ${dirPath}`);
  }
  return exists;
};

// 创建项目目录
export const createProjectDirectory = async (dirPath: string): Promise<void> => {
  try {
    await fs.ensureDir(dirPath);
    logger.success(`创建目录: ${dirPath}`);
  } catch (error) {
    logger.error(`创建目录失败: ${dirPath}`, error);
    throw error;
  }
};

// 更新package.json文件
export const updatePackageJson = async (
  projectDir: string, 
  updates: Record<string, any>
): Promise<void> => {
  const packagePath = path.join(projectDir, 'package.json');
  
  if (await fs.pathExists(packagePath)) {
    try {
      const packageJson = await fs.readJson(packagePath);
      
      // 合并更新
      const updatedPackageJson = { ...packageJson, ...updates };
      
      await fs.writeJson(packagePath, updatedPackageJson, { spaces: 2 });
      logger.success('package.json 更新完成');
    } catch (error) {
      logger.error('更新 package.json 失败:', error);
      throw error;
    }
  }
};